import axios from 'axios'
import MD5 from 'md5'

const server = axios.create({
  withCredentials: true,
  timeout: 3000
})

server.interceptors.request.use(
  (config) => {
    config.headers['x-platform'] = 'pc'
    config.headers['x-mall-code'] = 'SD001'

    if (config.method.toUpperCase() == 'GET') {
      let data = {}
      let str = ''
      data.timestamp = new Date().getTime()
      str += data.timestamp
      str += 'md5Key'
      data.sign = MD5(str)
    }

    if (config.method.toUpperCase() == 'POST') {
      let userInfo = localStorage.getItem('userInfo')
      config.headers['x-token'] = userInfo ? JSON.parse(userInfo).token : ''
      //需要传参数的请求
      if (config.data) {
        let arr = config.arr || []
        if (!arr) return console.log('请携带参数arr')
        let data = {}
        let str = ''
        arr.forEach((key) => {
          str += config.data[key]
        })
        data.timestamp = new Date().getTime()
        str += data.timestamp
        str += 'md5Key'
        data.sign = MD5(str)

        //整理config
        config.data = Object.assign(config.data, data)
      } else {
        //不需要传参数的请求
        let arr = config.arr || []
        if (!arr) return console.log('请携带参数arr')
        let data = {}
        let str = ''
        data.timestamp = new Date().getTime()
        str += data.timestamp
        str += 'md5Key'
        data.sign = MD5(str)
        config.data = data
      }
    }
    // console.log(config)
    return config
  },
  (err) => Promise.reject(err)
)

server.interceptors.response.use(
  (response) => {
    return response.data
  },
  (err) => Promise.reject(err)
)

export default server
